import pytest
import allure
from playwright.sync_api import Page, expect
import os
from datetime import datetime

def take_screenshot(page: Page, name: str):
    """Take a screenshot and save it with timestamp"""
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = f"screenshots/{name}_{timestamp}.png"
    os.makedirs("screenshots", exist_ok=True)
    page.screenshot(path=filename)
    return filename

@pytest.fixture(scope="function", autouse=True)
def setup_teardown(page: Page):
    # 在每个测试前执行
    page.set_viewport_size({"width": 1920, "height": 1080})
    yield
    # 在每个测试后执行
    if pytest.current_test.failed:
        take_screenshot(page, f"failed_{pytest.current_test.name}")

@allure.feature("登录功能")
@allure.story("登录基本功能")
class TestLogin:
    
    @allure.title("测试登录页面基本元素")
    @allure.severity(allure.severity_level.NORMAL)
    def test_login_page_elements(self, page: Page):
        """测试登录页面的基本元素是否存在"""
        with allure.step("导航到登录页面"):
            page.goto("http://localhost:8080")
        
        with allure.step("检查页面标题"):
            expect(page.locator("h2")).to_have_text("欢迎登录")
            expect(page.locator("p")).to_have_text("请使用您的账号密码登录系统")
        
        with allure.step("检查输入框"):
            username_input = page.locator('input[placeholder="请输入用户名"]')
            password_input = page.locator('input[placeholder="请输入密码"]')
            expect(username_input).to_be_visible()
            expect(password_input).to_be_visible()
        
        with allure.step("检查其他元素"):
            expect(page.get_by_text("记住我")).to_be_visible()
            expect(page.get_by_text("重置")).to_be_visible()
            expect(page.get_by_text("忘记密码？")).to_be_visible()
            expect(page.get_by_role("button", name="登录")).to_be_visible()
            expect(page.get_by_text("立即注册")).to_be_visible()

    @allure.title("测试登录成功场景")
    @allure.severity(allure.severity_level.CRITICAL)
    def test_login_success(self, page: Page):
        """测试登录成功场景"""
        with allure.step("导航到登录页面"):
            page.goto("http://localhost:8080")
        
        with allure.step("输入有效的用户名和密码"):
            page.locator('input[placeholder="请输入用户名"]').fill("suyuxi")
            page.locator('input[placeholder="请输入密码"]').fill("Aa123456")
        
        with allure.step("点击登录按钮"):
            page.get_by_role("button", name="登录").click()
        
        with allure.step("等待登录成功后的跳转"):
            page.wait_for_url("**/testplanform/home")
        
        with allure.step("验证本地存储中是否保存了用户信息"):
            expect(page.evaluate("localStorage.getItem('username')")).to_be_truthy()
            expect(page.evaluate("localStorage.getItem('token')")).to_be_truthy()

    @allure.title("测试登录失败场景")
    @allure.severity(allure.severity_level.CRITICAL)
    def test_login_failure(self, page: Page):
        """测试登录失败场景"""
        with allure.step("导航到登录页面"):
            page.goto("http://localhost:8080")
        
        with allure.step("输入无效的用户名和密码"):
            page.locator('input[placeholder="请输入用户名"]').fill("suyuxi")
            page.locator('input[placeholder="请输入密码"]').fill("Aa123456789")
        
        with allure.step("点击登录按钮"):
            page.get_by_role("button", name="登录").click()
        
        with allure.step("等待错误消息出现"):
            error_message = page.locator('.el-message--error')
            expect(error_message).to_be_visible()
        
        with allure.step("验证密码字段被清空"):
            expect(page.locator('input[placeholder="请输入密码"]')).to_have_value("")

    @allure.title("测试记住我功能")
    @allure.severity(allure.severity_level.NORMAL)
    def test_remember_me(self, page: Page):
        """测试记住我功能"""
        with allure.step("导航到登录页面"):
            page.goto("http://localhost:8080")
        
        with allure.step('输入凭据并勾选"记住我"'):
            page.locator('input[placeholder="请输入用户名"]').fill("suyuxi")
            page.locator('input[placeholder="请输入密码"]').fill("Aa123456")
            page.get_by_text("记住我").click()
        
        with allure.step("点击登录"):
            page.get_by_role("button", name="登录").click()
        
        with allure.step("等待登录成功"):
            page.wait_for_url("**/testplanform/home")
        
        with allure.step("刷新页面"):
            page.reload()
        
        with allure.step("验证凭据是否被保存"):
            saved_credentials = page.evaluate("localStorage.getItem('savedCredentials')")
            assert saved_credentials is not None
    
    @allure.title("测试重置表单功能")
    @allure.severity(allure.severity_level.MINOR)
    def test_reset_form(self, page: Page):
        """测试重置表单功能"""
        with allure.step("导航到登录页面"):
            page.goto("http://localhost:8080")
        
        with allure.step("输入一些数据"):
            page.locator('input[placeholder="请输入用户名"]').fill("suyuxi")
            page.locator('input[placeholder="请输入密码"]').fill("Aa123456")
        
        with allure.step("点击重置"):
            page.get_by_text("重置").click()
        
        with allure.step("验证表单被清空"):
            expect(page.locator('input[placeholder="请输入用户名"]')).to_have_value("")
            expect(page.locator('input[placeholder="请输入密码"]')).to_have_value("")

    @allure.title("测试导航链接")
    @allure.severity(allure.severity_level.MINOR)
    def test_navigation_links(self, page: Page):
        """测试导航链接"""
        with allure.step("导航到登录页面"):
            page.goto("http://localhost:8080")
        
        with allure.step("测试忘记密码链接"):
            page.get_by_text("忘记密码？").click()
            page.wait_for_url("**/forgotpassword")
        
        with allure.step("返回登录页面"):
            page.goto("http://localhost:8080")
        
        with allure.step("测试注册链接"):
            page.get_by_text("立即注册").click()
            page.wait_for_url("**/register") 